<?php

namespace App\Repositories\System;


use App\Models\System\Menu;
use App\Repositories\Repository;
use Illuminate\Http\Request;

/**
 *
 */
class MenuRepository extends Repository
{
    private $menu_tree_key;
    private $redis;
    private $lib_cat;

    public function __construct(Request $request, \App\Lib\Utils\Category $cat)
    {
        parent::__construct($request);
        $this->redis = app('phpredis');
        $this->redis_key = config('rediskey.system.menu');
        $this->menu_tree_key = config('rediskey.system.menu_tree');
        $this->lib_cat = $cat;
    }

    public function list($type)
    {
        $menu = Menu::query()->where('status', 0)
            ->where('type',$type)
            ->orderBy('sort', 'desc')->get()->toArray();
        if ($menu) {
            $menu = $this->lib_cat->getTree($menu);
        }
        return $this->respondWith($menu);
    }

    public function tree($type)
    {
        $menu = $this->redis->get($this->menu_tree_key . $type);
        $menu = json_decode($menu, true);
        if (!$menu) {
            $menu = Menu::query()->orderBy('sort', 'desc')
                ->where('type',$type)->get()->toArray();
            if ($menu) {
                $menu = $this->lib_cat->getDeepTree($menu, 'pid', 'menu_id');
                $this->redis->set($this->menu_tree_key . $type, json_encode($menu));
            }
        }
        return $this->respondWith($menu);
    }

    public function show($id)
    {
        $menu = Menu::query()->find($id);
        return $this->respondWith($menu);
    }

    public function store($data)
    {
        try {
            Menu::query()->create($data);
            $this->redis->del($this->menu_tree_key . '*');
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->throwRespondError(10108);
        }
    }

    public function save($data)
    {
        $category = Menu::query()->find($data['menu_id']);
        if ($category) {
            try {
                $category->fill($data)->save();
                $this->redis->del($this->menu_tree_key . '*');
                return $this->respondSuccess();
            } catch (\Exception $e) {
                return $this->throwRespondError(10106);
            }
        }
        return $this->respondError(10106);
    }

    public function del($id)
    {
        $menu = Menu::query()->get()->toArray();
        $had = $this->lib_cat->haveChild($id, $menu);
        if ($had) {
            return $this->throwRespondError(10801);
        }

        try {
            Menu::query()->where("menu_id", "=", $id)->delete();
            $this->redis->del($this->menu_tree_key . '*');
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10107);
        }
    }


}

